package com.gen.info.generate_cluster_information.service;

import com.gen.info.generate_cluster_information.config.TargetDataSource;
import com.gen.info.generate_cluster_information.mode.ConnectionInfo;
import com.gen.info.generate_cluster_information.mode.OceanBaseClusterInfoDO;
import com.gen.info.generate_cluster_information.mode.UserDataBaseInfo;
import com.gen.info.generate_cluster_information.mode.UserInfo;
import com.gen.info.generate_cluster_information.util.CommonUtil;
import com.gen.info.generate_cluster_information.util.DBUtil;
import com.gen.info.generate_cluster_information.util.OceanBaseSqlObjectGenerateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

@Service
@Slf4j
public class CreateDatabaseUser {
    @Autowired
    private TargetDataSource targetDataSource;
    public  void createDBRS(Collection<OceanBaseClusterInfoDO> clusterInfoDOS){
        //构建连接信息
        ConnectionInfo connectionInfo = new ConnectionInfo();
        BeanUtils.copyProperties(targetDataSource,connectionInfo);
        log.info("连接信息构建完成："+connectionInfo.toString());

        for (OceanBaseClusterInfoDO clusterInfoDO : clusterInfoDOS) {
            //设置租户名
            connectionInfo.setTenant_name(clusterInfoDO.getTenant());
            final ArrayList<String> databaseList = new ArrayList<>();
            final ArrayList<String> users = new ArrayList<>();
            final ArrayList<String> passwords = new ArrayList<>();
            clusterInfoDO.getDatabases().forEach(d->{
                databaseList.add(d);
            });
            clusterInfoDO.getUsers().forEach(u->{
                users.add(u);
            });
            clusterInfoDO.getPassword().forEach(p->{
                passwords.add(p);
            });
            //一个租户建立一个连接来创建数据库和用户
            try {
                final Connection connetcion = DBUtil.getConnetcion(connectionInfo);
                final Statement stmt = DBUtil.getCreateStatement(connetcion);
                //获取数据库的集合
                final ArrayList<String> dataBaseSql = OceanBaseSqlObjectGenerateUtil.getDataBaseSql(databaseList);
                for (String sql : dataBaseSql) {
                    stmt.addBatch(sql);
                }
                stmt.executeBatch();
                stmt.clearBatch();
                log.info("创建数据库完毕！！");
                //组合用户信息
                final ArrayList<UserInfo> userInfos = new ArrayList<>();
                if (users.size()==passwords.size()){
                    for (int i = 0; i < users.size(); i++) {
                        userInfos.add(new UserInfo(users.get(i),passwords.get(i)));
                    }
                 log.info("组合用户信息完毕："+userInfos);
                    final ArrayList<String> userSql = OceanBaseSqlObjectGenerateUtil.getUserSql(userInfos);
                    for (String usersql : userSql) {
                        stmt.addBatch(usersql);
                    }
                    stmt.executeBatch();
                    stmt.clearBatch();
                    log.info("用户创建完毕！");
                }else {
                    log.info("用户信息数量与密码不匹配");
                }
                log.info("开始组建用户和数据库进行授权");
                log.info("commitdb的权限："+targetDataSource.getCommon_db().toString());
                if (targetDataSource.getCommon_db()!=null){
                    final ArrayList<UserDataBaseInfo> db_userInfos = new ArrayList<>();
                    if (users.size()==databaseList.size()){
                        for (int i = 0; i < users.size(); i++) {
                            db_userInfos.add(new UserDataBaseInfo(users.get(i),databaseList.get(i)));
                        }
                    }
                    log.info("组建用户和数据库完成："+db_userInfos);
                    log.info("开始授权");
                    final ArrayList<String> authSql = OceanBaseSqlObjectGenerateUtil.getAuthSql(db_userInfos,targetDataSource.getCommon_db());
                    for (String sql : authSql) {
                        stmt.addBatch(sql);
                    }
                    stmt.executeBatch();
                    stmt.clearBatch();
                }
                log.info("开始授予mysql库的"+targetDataSource.getMysql_db()
                        +"和oceanbase库的"+targetDataSource.getOceanbase_db()+"权限");
                if (targetDataSource.getMysql_db()!=null){
                    final String mySqlAuthList = CommonUtil.getAuthList(targetDataSource.getMysql_db());
                    for (String user : users) {
                        stmt.addBatch("grant "+mySqlAuthList+" on mysql.* to "+user);
                    }
                }
                if (targetDataSource.getOceanbase_db()!=null){
                    final String oceanBaseAuthList = CommonUtil.getAuthList(targetDataSource.getOceanbase_db());
                    for (String user : users) {
                        stmt.addBatch("grant "+oceanBaseAuthList+" on oceanbase.* to "+user);
                    }
                }
                stmt.executeBatch();
                stmt.clearBatch();
                log.info("授权结束");

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                DBUtil.closeConnection();
            }

            log.info(clusterInfoDO.getTenant()+"租户所对应的用户："+
                    clusterInfoDO.getDatabases());
            log.info(clusterInfoDO.getTenant()
                    +"租户所对应的数据库："+clusterInfoDO.getUsers());
        }
    }
}
